#!/usr/bin/env python3
"""
检测区域配置对话框
统一管理所有触发器的检测区域设置
"""

import pyautogui
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QPushButton,
                              QLabel, QListWidget, QListWidgetItem, QWidget,
                              QFormLayout, QGroupBox, QComboBox, QSpinBox,
                              QCheckBox, QTabWidget, QTextEdit, QSplitter,
                              QFrame, QScrollArea, QMessageBox)
from PySide6.QtCore import Qt, QTimer
from PySide6.QtGui import QFont, QColor, QPalette

class DetectionAreaConfigDialog(QDialog):
    """检测区域配置对话框"""

    def __init__(self, color_triggers, parent=None):
        super().__init__(parent)
        self.color_triggers = color_triggers
        self.current_trigger = None
        self.preview_window = None

        self.setWindowTitle("检测区域配置管理")
        self.setGeometry(200, 200, 900, 700)
        self.setModal(True)

        self.setup_ui()
        self.load_trigger_list()

    def setup_ui(self):
        """设置UI界面"""
        layout = QHBoxLayout(self)

        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        layout.addWidget(splitter)

        # 左侧：触发器列表
        self.setup_trigger_list(splitter)

        # 右侧：配置面板
        self.setup_config_panel(splitter)

        # 底部按钮
        self.setup_bottom_buttons(layout)

        # 设置分割器比例
        splitter.setSizes([300, 600])

    def setup_trigger_list(self, parent):
        """设置触发器列表"""
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)

        # 标题
        title_label = QLabel("颜色触发器列表")
        title_font = QFont()
        title_font.setPointSize(12)
        title_font.setBold(True)
        title_label.setFont(title_font)
        left_layout.addWidget(title_label)

        # 触发器列表
        self.trigger_list = QListWidget()
        self.trigger_list.currentItemChanged.connect(self.on_trigger_selected)
        left_layout.addWidget(self.trigger_list)

        # 列表操作按钮
        list_button_layout = QHBoxLayout()

        self.refresh_btn = QPushButton("刷新列表")
        self.refresh_btn.clicked.connect(self.load_trigger_list)
        list_button_layout.addWidget(self.refresh_btn)

        self.apply_all_btn = QPushButton("应用到全部")
        self.apply_all_btn.clicked.connect(self.apply_to_all_triggers)
        list_button_layout.addWidget(self.apply_all_btn)

        left_layout.addLayout(list_button_layout)

        parent.addWidget(left_widget)

    def setup_config_panel(self, parent):
        """设置配置面板"""
        right_widget = QWidget()
        right_layout = QVBoxLayout(right_widget)

        # 标题
        config_title = QLabel("检测区域配置")
        config_font = QFont()
        config_font.setPointSize(12)
        config_font.setBold(True)
        config_title.setFont(config_font)
        right_layout.addWidget(config_title)

        # 创建标签页
        self.tab_widget = QTabWidget()
        right_layout.addWidget(self.tab_widget)

        # 基础配置标签页
        self.setup_basic_config_tab()

        # 高级配置标签页
        self.setup_advanced_config_tab()

        # 预览和信息标签页
        self.setup_preview_tab()

        parent.addWidget(right_widget)

    def setup_basic_config_tab(self):
        """设置基础配置标签页"""
        basic_tab = QWidget()
        layout = QVBoxLayout(basic_tab)

        # 启用检测区域
        enable_group = QGroupBox("检测方法选择")
        enable_layout = QFormLayout(enable_group)

        self.enable_advanced_cb = QCheckBox("启用高级检测区域")
        self.enable_advanced_cb.toggled.connect(self.on_advanced_enabled_changed)
        enable_layout.addRow(self.enable_advanced_cb)

        self.detection_method_combo = QComboBox()
        self.detection_method_combo.addItems([
            "dominant_kmeans", "traditional", "kmeans", "hybrid"
        ])
        self.detection_method_combo.currentTextChanged.connect(self.on_config_changed)
        enable_layout.addRow("检测方法:", self.detection_method_combo)

        layout.addWidget(enable_group)

        # 区域大小配置
        size_group = QGroupBox("区域大小配置")
        size_layout = QFormLayout(size_group)

        self.region_size_spin = QSpinBox()
        self.region_size_spin.setRange(50, 500)
        self.region_size_spin.setSingleStep(10)
        self.region_size_spin.setValue(200)
        self.region_size_spin.valueChanged.connect(self.on_config_changed)
        size_layout.addRow("区域大小 (像素):", self.region_size_spin)

        # 快速设置按钮
        size_buttons_layout = QHBoxLayout()
        for size in [100, 150, 200, 250, 300]:
            btn = QPushButton(f"{size}")
            btn.setFixedWidth(50)
            btn.clicked.connect(lambda checked, s=size: self.region_size_spin.setValue(s))
            size_buttons_layout.addWidget(btn)
        size_layout.addRow("快速设置:", size_buttons_layout)

        layout.addWidget(size_group)

        # 位置偏移配置
        offset_group = QGroupBox("位置偏移配置")
        offset_layout = QFormLayout(offset_group)

        self.offset_x_spin = QSpinBox()
        self.offset_x_spin.setRange(-500, 500)
        self.offset_x_spin.setValue(0)
        self.offset_x_spin.valueChanged.connect(self.on_config_changed)
        offset_layout.addRow("X偏移 (像素):", self.offset_x_spin)

        self.offset_y_spin = QSpinBox()
        self.offset_y_spin.setRange(-500, 500)
        self.offset_y_spin.setValue(0)
        self.offset_y_spin.valueChanged.connect(self.on_config_changed)
        offset_layout.addRow("Y偏移 (像素):", self.offset_y_spin)

        layout.addWidget(offset_group)

        self.tab_widget.addTab(basic_tab, "基础配置")

    def setup_advanced_config_tab(self):
        """设置高级配置标签页"""
        advanced_tab = QWidget()
        layout = QVBoxLayout(advanced_tab)

        # K-Means参数
        kmeans_group = QGroupBox("K-Means参数")
        kmeans_layout = QFormLayout(kmeans_group)

        self.clusters_spin = QSpinBox()
        self.clusters_spin.setRange(2, 8)
        self.clusters_spin.setValue(3)
        self.clusters_spin.valueChanged.connect(self.on_config_changed)
        kmeans_layout.addRow("聚类数量:", self.clusters_spin)

        self.tolerance_spin = QSpinBox()
        self.tolerance_spin.setRange(10, 100)
        self.tolerance_spin.setValue(30)
        self.tolerance_spin.valueChanged.connect(self.on_config_changed)
        kmeans_layout.addRow("颜色容差:", self.tolerance_spin)

        layout.addWidget(kmeans_group)

        # 游戏预设
        preset_group = QGroupBox("游戏场景预设")
        preset_layout = QVBoxLayout(preset_group)

        preset_buttons_layout = QHBoxLayout()

        fps_btn = QPushButton("FPS游戏")
        fps_btn.clicked.connect(lambda: self.apply_preset("fps"))
        preset_buttons_layout.addWidget(fps_btn)

        moba_btn = QPushButton("MOBA游戏")
        moba_btn.clicked.connect(lambda: self.apply_preset("moba"))
        preset_buttons_layout.addWidget(moba_btn)

        rpg_btn = QPushButton("RPG游戏")
        rpg_btn.clicked.connect(lambda: self.apply_preset("rpg"))
        preset_buttons_layout.addWidget(rpg_btn)

        preset_layout.addLayout(preset_buttons_layout)

        # 预设说明
        preset_info = QLabel(
            "FPS: 200x200区域，适合敌人检测\n"
            "MOBA: 120x120区域，适合UI检测\n"
            "RPG: 150x150区域，适合物品检测"
        )
        preset_info.setStyleSheet("color: gray; font-size: 10px;")
        preset_layout.addWidget(preset_info)

        layout.addWidget(preset_group)

        # 批量操作
        batch_group = QGroupBox("批量操作")
        batch_layout = QVBoxLayout(batch_group)

        batch_buttons_layout = QHBoxLayout()

        self.copy_to_all_btn = QPushButton("复制到全部")
        self.copy_to_all_btn.clicked.connect(self.copy_config_to_all)
        batch_buttons_layout.addWidget(self.copy_to_all_btn)

        self.reset_all_btn = QPushButton("重置全部")
        self.reset_all_btn.clicked.connect(self.reset_all_configs)
        batch_buttons_layout.addWidget(self.reset_all_btn)

        batch_layout.addLayout(batch_buttons_layout)
        layout.addWidget(batch_group)

        self.tab_widget.addTab(advanced_tab, "高级配置")

    def setup_preview_tab(self):
        """设置预览和信息标签页"""
        preview_tab = QWidget()
        layout = QVBoxLayout(preview_tab)

        # 区域信息显示
        info_group = QGroupBox("区域信息")
        info_layout = QVBoxLayout(info_group)

        self.area_info_label = QLabel()
        self.area_info_label.setStyleSheet(
            "background-color: #f0f0f0; padding: 10px; border: 1px solid #ccc; "
            "font-family: monospace; font-size: 11px;"
        )
        self.area_info_label.setWordWrap(True)
        info_layout.addWidget(self.area_info_label)

        layout.addWidget(info_group)

        # 预览控制
        preview_group = QGroupBox("预览控制")
        preview_layout = QVBoxLayout(preview_group)

        preview_buttons_layout = QHBoxLayout()

        self.preview_btn = QPushButton("预览检测区域")
        self.preview_btn.clicked.connect(self.preview_detection_area)
        preview_buttons_layout.addWidget(self.preview_btn)

        self.hide_preview_btn = QPushButton("隐藏预览")
        self.hide_preview_btn.clicked.connect(self.hide_preview)
        preview_buttons_layout.addWidget(self.hide_preview_btn)

        preview_layout.addLayout(preview_buttons_layout)
        layout.addWidget(preview_group)

        # 配置日志
        log_group = QGroupBox("配置日志")
        log_layout = QVBoxLayout(log_group)

        self.config_log = QTextEdit()
        self.config_log.setMaximumHeight(150)
        self.config_log.setReadOnly(True)
        log_layout.addWidget(self.config_log)

        layout.addWidget(log_group)

        self.tab_widget.addTab(preview_tab, "预览信息")

    def setup_bottom_buttons(self, parent_layout):
        """设置底部按钮"""
        button_layout = QHBoxLayout()

        self.apply_btn = QPushButton("应用配置")
        self.apply_btn.clicked.connect(self.apply_current_config)
        button_layout.addWidget(self.apply_btn)

        button_layout.addStretch()

        self.ok_btn = QPushButton("确定")
        self.ok_btn.clicked.connect(self.accept)
        button_layout.addWidget(self.ok_btn)

        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_btn)

        parent_layout.addLayout(button_layout)

    def load_trigger_list(self):
        """加载触发器列表"""
        self.trigger_list.clear()

        for i, trigger in enumerate(self.color_triggers):
            item = QListWidgetItem()

            # 创建触发器显示组件
            widget = QWidget()
            layout = QHBoxLayout(widget)
            layout.setContentsMargins(5, 2, 5, 2)

            # 颜色显示
            color_label = QLabel()
            color_label.setFixedSize(20, 20)
            color_label.setStyleSheet(f"background-color: rgb{trigger.color}; border: 1px solid black;")
            layout.addWidget(color_label)

            # 触发器名称
            name_label = QLabel(trigger.name)
            layout.addWidget(name_label)

            # 检测方法显示
            method = getattr(trigger, 'detection_method', 'traditional')
            method_label = QLabel(f"[{method}]")
            method_label.setStyleSheet("color: gray; font-size: 10px;")
            layout.addWidget(method_label)

            layout.addStretch()

            # 设置项目
            item.setSizeHint(widget.sizeHint())
            self.trigger_list.addItem(item)
            self.trigger_list.setItemWidget(item, widget)

            # 存储触发器索引
            item.setData(Qt.UserRole, i)

        self.log_message(f"已加载 {len(self.color_triggers)} 个触发器")

    def on_trigger_selected(self, current, previous):
        """触发器选择改变"""
        if current is None:
            self.current_trigger = None
            self.clear_config_panel()
            return

        trigger_index = current.data(Qt.UserRole)
        if 0 <= trigger_index < len(self.color_triggers):
            self.current_trigger = self.color_triggers[trigger_index]
            self.load_trigger_config()
            self.log_message(f"选择触发器: {self.current_trigger.name}")

    def load_trigger_config(self):
        """加载触发器配置到界面"""
        if not self.current_trigger:
            return

        trigger = self.current_trigger

        # 检测方法
        method = getattr(trigger, 'detection_method', 'traditional')
        is_advanced = method != 'traditional'

        self.enable_advanced_cb.setChecked(is_advanced)
        self.detection_method_combo.setCurrentText(method)

        # 区域配置
        self.region_size_spin.setValue(getattr(trigger, 'dominant_region_size', 200))
        self.offset_x_spin.setValue(getattr(trigger, 'dominant_center_offset_x', 0))
        self.offset_y_spin.setValue(getattr(trigger, 'dominant_center_offset_y', 0))

        # K-Means参数
        self.clusters_spin.setValue(getattr(trigger, 'kmeans_clusters', 3))
        self.tolerance_spin.setValue(getattr(trigger, 'tolerance', 30))

        # 更新界面状态
        self.on_advanced_enabled_changed(is_advanced)
        self.update_area_info()

    def clear_config_panel(self):
        """清空配置面板"""
        self.enable_advanced_cb.setChecked(False)
        self.detection_method_combo.setCurrentText("traditional")
        self.region_size_spin.setValue(200)
        self.offset_x_spin.setValue(0)
        self.offset_y_spin.setValue(0)
        self.clusters_spin.setValue(3)
        self.tolerance_spin.setValue(30)
        self.area_info_label.setText("请选择一个触发器")

    def on_advanced_enabled_changed(self, enabled):
        """高级检测启用状态改变"""
        # 启用/禁用相关控件
        controls = [
            self.detection_method_combo, self.region_size_spin, self.offset_x_spin,
            self.offset_y_spin, self.clusters_spin, self.tolerance_spin
        ]

        for control in controls:
            control.setEnabled(enabled)

        if not enabled:
            self.detection_method_combo.setCurrentText("traditional")

        self.on_config_changed()

    def on_config_changed(self):
        """配置改变时更新信息"""
        self.update_area_info()

    def update_area_info(self):
        """更新区域信息显示"""
        try:
            screen_width, screen_height = pyautogui.size()
            center_x, center_y = screen_width // 2, screen_height // 2

            region_size = self.region_size_spin.value()
            offset_x = self.offset_x_spin.value()
            offset_y = self.offset_y_spin.value()

            # 计算实际检测中心
            actual_center_x = center_x + offset_x
            actual_center_y = center_y + offset_y

            # 计算区域边界
            half_size = region_size // 2
            left = actual_center_x - half_size
            top = actual_center_y - half_size
            right = actual_center_x + half_size
            bottom = actual_center_y + half_size

            # 检查边界
            in_bounds = (left >= 0 and top >= 0 and
                        right <= screen_width and bottom <= screen_height)

            pixel_count = region_size * region_size

            # 检测方法信息
            method = self.detection_method_combo.currentText()
            enabled = self.enable_advanced_cb.isChecked()

            info_text = f"检测方法: {'高级' if enabled else '传统'} ({method})\n"
            info_text += f"屏幕尺寸: {screen_width} x {screen_height}\n"
            info_text += f"屏幕中心: ({center_x}, {center_y})\n"
            info_text += f"检测中心: ({actual_center_x}, {actual_center_y})\n"
            info_text += f"区域范围: ({left}, {top}) 到 ({right}, {bottom})\n"
            info_text += f"区域大小: {region_size}x{region_size} ({pixel_count:,} 像素)\n"
            info_text += f"偏移量: X={offset_x}, Y={offset_y}\n"

            if enabled:
                info_text += f"聚类数量: {self.clusters_spin.value()}\n"
                info_text += f"颜色容差: {self.tolerance_spin.value()}\n"

            info_text += f"边界检查: {'✅ 正常' if in_bounds else '❌ 超出屏幕'}"

            self.area_info_label.setText(info_text)

            # 根据边界检查设置颜色
            if in_bounds:
                self.area_info_label.setStyleSheet(
                    "background-color: #e8f5e8; padding: 10px; border: 1px solid #4caf50; "
                    "font-family: monospace; font-size: 11px;"
                )
            else:
                self.area_info_label.setStyleSheet(
                    "background-color: #ffeaea; padding: 10px; border: 1px solid #f44336; "
                    "font-family: monospace; font-size: 11px;"
                )

        except Exception as e:
            self.area_info_label.setText(f"计算错误: {e}")

    def apply_preset(self, preset_type):
        """应用游戏预设"""
        presets = {
            "fps": {
                "method": "dominant_kmeans",
                "region_size": 200,
                "clusters": 3,
                "tolerance": 40,
                "offset_x": 0,
                "offset_y": 0
            },
            "moba": {
                "method": "dominant_kmeans",
                "region_size": 120,
                "clusters": 2,
                "tolerance": 25,
                "offset_x": 0,
                "offset_y": 0
            },
            "rpg": {
                "method": "dominant_kmeans",
                "region_size": 150,
                "clusters": 3,
                "tolerance": 35,
                "offset_x": 0,
                "offset_y": 0
            }
        }

        if preset_type in presets:
            preset = presets[preset_type]

            self.enable_advanced_cb.setChecked(True)
            self.detection_method_combo.setCurrentText(preset["method"])
            self.region_size_spin.setValue(preset["region_size"])
            self.clusters_spin.setValue(preset["clusters"])
            self.tolerance_spin.setValue(preset["tolerance"])
            self.offset_x_spin.setValue(preset["offset_x"])
            self.offset_y_spin.setValue(preset["offset_y"])

            self.log_message(f"已应用 {preset_type.upper()} 游戏预设")

    def preview_detection_area(self):
        """预览检测区域"""
        try:
            region_size = self.region_size_spin.value()
            offset_x = self.offset_x_spin.value()
            offset_y = self.offset_y_spin.value()

            screen_width, screen_height = pyautogui.size()
            center_x, center_y = screen_width // 2, screen_height // 2
            actual_center_x = center_x + offset_x
            actual_center_y = center_y + offset_y
            half_size = region_size // 2
            left = actual_center_x - half_size
            top = actual_center_y - half_size

            # 隐藏现有预览
            self.hide_preview()

            # 使用Qt创建预览窗口
            from PySide6.QtWidgets import QWidget, QLabel, QVBoxLayout
            from PySide6.QtCore import QTimer

            self.preview_window = QWidget()
            self.preview_window.setWindowTitle("检测区域预览")
            self.preview_window.setGeometry(left, top, region_size, region_size)
            self.preview_window.setWindowFlags(self.preview_window.windowFlags() | Qt.WindowStaysOnTopHint)

            # 设置半透明红色背景
            self.preview_window.setStyleSheet("""
                QWidget {
                    background-color: rgba(255, 0, 0, 100);
                    border: 2px solid red;
                }
                QLabel {
                    color: white;
                    font-size: 14px;
                    font-weight: bold;
                    background-color: transparent;
                }
            """)

            layout = QVBoxLayout(self.preview_window)
            label = QLabel(f"检测区域\n{region_size}x{region_size}")
            label.setAlignment(Qt.AlignCenter)
            layout.addWidget(label)

            self.preview_window.show()

            self.log_message(f"预览检测区域: {region_size}x{region_size} at ({left}, {top})")

        except Exception as e:
            self.log_message(f"预览失败: {e}")

    def hide_preview(self):
        """隐藏预览窗口"""
        if self.preview_window:
            self.preview_window.close()
            self.preview_window = None

    def apply_current_config(self):
        """应用当前配置到选中的触发器"""
        if not self.current_trigger:
            QMessageBox.warning(self, "警告", "请先选择一个触发器")
            return

        trigger = self.current_trigger

        # 应用配置
        if self.enable_advanced_cb.isChecked():
            trigger.detection_method = self.detection_method_combo.currentText()
            trigger.dominant_region_size = self.region_size_spin.value()
            trigger.dominant_center_offset_x = self.offset_x_spin.value()
            trigger.dominant_center_offset_y = self.offset_y_spin.value()
            trigger.kmeans_clusters = self.clusters_spin.value()
            trigger.tolerance = self.tolerance_spin.value()
        else:
            trigger.detection_method = "traditional"

        self.log_message(f"已应用配置到触发器: {trigger.name}")

        # 刷新列表显示
        self.load_trigger_list()

    def copy_config_to_all(self):
        """复制当前配置到所有触发器"""
        if not self.current_trigger:
            QMessageBox.warning(self, "警告", "请先选择一个触发器作为模板")
            return

        reply = QMessageBox.question(self, "确认",
                                   f"确定要将当前配置复制到所有 {len(self.color_triggers)} 个触发器吗？",
                                   QMessageBox.Yes | QMessageBox.No)

        if reply == QMessageBox.Yes:
            # 获取当前配置
            config = {
                'enabled': self.enable_advanced_cb.isChecked(),
                'method': self.detection_method_combo.currentText(),
                'region_size': self.region_size_spin.value(),
                'offset_x': self.offset_x_spin.value(),
                'offset_y': self.offset_y_spin.value(),
                'clusters': self.clusters_spin.value(),
                'tolerance': self.tolerance_spin.value()
            }

            # 应用到所有触发器
            for trigger in self.color_triggers:
                if config['enabled']:
                    trigger.detection_method = config['method']
                    trigger.dominant_region_size = config['region_size']
                    trigger.dominant_center_offset_x = config['offset_x']
                    trigger.dominant_center_offset_y = config['offset_y']
                    trigger.kmeans_clusters = config['clusters']
                    trigger.tolerance = config['tolerance']
                else:
                    trigger.detection_method = "traditional"

            self.log_message(f"已将配置复制到所有 {len(self.color_triggers)} 个触发器")
            self.load_trigger_list()

    def reset_all_configs(self):
        """重置所有触发器配置"""
        reply = QMessageBox.question(self, "确认",
                                   f"确定要重置所有 {len(self.color_triggers)} 个触发器的检测区域配置吗？",
                                   QMessageBox.Yes | QMessageBox.No)

        if reply == QMessageBox.Yes:
            for trigger in self.color_triggers:
                trigger.detection_method = "traditional"
                # 移除高级检测属性
                for attr in ['dominant_region_size', 'dominant_center_offset_x',
                           'dominant_center_offset_y', 'kmeans_clusters']:
                    if hasattr(trigger, attr):
                        delattr(trigger, attr)

            self.log_message(f"已重置所有 {len(self.color_triggers)} 个触发器配置")
            self.load_trigger_list()
            self.clear_config_panel()

    def apply_to_all_triggers(self):
        """应用当前配置到所有触发器"""
        self.copy_config_to_all()

    def log_message(self, message):
        """记录日志消息"""
        import datetime
        timestamp = datetime.datetime.now().strftime("%H:%M:%S")
        self.config_log.append(f"[{timestamp}] {message}")

    def closeEvent(self, event):
        """关闭事件"""
        self.hide_preview()
        super().closeEvent(event)
